<template>
  <div>
    <div class="top">
      <!-- 头部标题 -->
      <!-- <div> -->
      <h1 class="title01">土壤监测</h1>
      <!-- </div> -->
      <!-- 搜索框 -->
      <div class="right">
        <el-form :model="Inquireform" label-width="auto">
          <div class="query">
            <el-input
              v-model.trim="Inquireform.searchText"
              style="max-width: 600px"
              placeholder="请先选择要搜索的类型"
              class="input-with-select"
              clearable
            >
              <template #prepend>
                <el-select
                  v-model="Inquireform.search"
                  placeholder="搜索模式"
                  style="width: 100px"
                  clearable
                >
                  <el-option label="湿度" value="hum" />
                  <el-option label="PH值" value="ph" />
                  <el-option label="植物名" value="plantname" />
                </el-select>
              </template>
            </el-input>
            <!-- <el-input
              v-model.trim="Inquireform.searchText"
              @input="handleQuery"
              placeholder="输入设备名进行查询"
            ></el-input> -->
            <el-button type="primary" @click="Search(Inquireform)"
              >搜索</el-button
            >
          </div>
        </el-form>
        <div>
          <el-button
            type="primary"
            @click="handleAddNew"
            :disabled="soil.data === null"
            >新增</el-button
          >
        </div>
      </div>
    </div>
    <div>
      <!-- 列表数据 -->
      <el-table :data="indexedData" style="width: 100%" empty-text="暂无数据">
        <el-table-column fixed prop="index" label="序号" width="80" />
        <el-table-column prop="plantname" label="植物名" width="80" />
        <el-table-column prop="ph" label="ph值(ph)" width="130">
          <template #default="scope">
            <span> {{ scope.row.ph ? scope.row.ph + " ph" : "" }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="phmax" label="ph值上限(PH)">
          <template #default="scope">
            <span :class="scope.row.phmax < scope.row.ph ? 'max' : 'null'">
              {{ scope.row.phmax + " ph" }}</span
            >
          </template>
        </el-table-column>
        <el-table-column prop="phmin" label="ph值下限(ph)">
          <template #default="scope">
            <span :class="scope.row.phmin > scope.row.ph ? 'max' : 'null'">
              {{ scope.row.phmin + " ph" }}</span
            >
          </template>
        </el-table-column>
        <!-- <el-table-column prop="dname" label="设备名" width="120" /> -->
        <el-table-column prop="hum" label="土壤湿度(毫升)" width="150" />
        <el-table-column prop="hummax" label="土壤湿度上限">
          <template #default="scope">
            <span :class="scope.row.hummax < scope.row.hum ? 'max' : 'null'">
              {{ scope.row.hummax + "%" }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="hummin" label="土壤湿度下限">
          <template #default="scope">
            <span :class="scope.row.hummin > scope.row.hum ? 'max' : 'null'">
              {{ scope.row.hummin + "%" }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="createtime" label="开始时间" />
        <el-table-column prop="endtime" label="结束时间" />
        <el-table-column prop="username" label="创建人" />
        <el-table-column prop="remark" label="删除原因" width="120" />
        <el-table-column fixed="right" label="操作" width="100">
          <template #default="scope">
            <!-- <el-button
              link
              type="primary"
              size="small"
              @click="openEditDialog(scope.row)"
              :class="{ deleted: scope.row.deleted === 1 }"
              :disabled="scope.row.deleted === 1"
              >编辑</el-button
            > -->
            <el-button
              link
              type="primary"
              size="small"
              @click="openEditDelete(scope.row)"
              :class="{ deleted: scope.row.deleted === 1 }"
              :disabled="scope.row.deleted === 1"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 删除通知 -->
    <el-dialog v-model="dialogFormDelate" title="删除" width="500">
      <el-form :model="form" ref="ruleFormRefDelete" :rules="soilRules">
        <el-form-item
          label="删除原因"
          :label-width="formLabelWidth"
          prop="remark"
        >
          <el-input
            v-model.trim="form.remark"
            :rows="2"
            type="textarea"
            placeholder="请输入备注"
            maxlength="30"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogFormDelate = false">取消</el-button>
          <el-button type="primary" @click="submitDelete(ruleFormRefDelete)">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 分页 -->
    <div>
      <div class="example-pagination-block">
        <el-pagination
          layout="prev, pager, next"
          :total="total"
          :current-page="currentPage"
          :pageSize="pageSize"
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
        />
      </div>
    </div>
    <!-- 新增弹窗 -->
    <div>
      <el-dialog v-model="dialogFormVisibleAdd" title="新增" width="500">
        <el-form :model="form" ref="ruleFormRef" :rules="soilRules">
          <!-- 新增植物名 -->
          <!-- <el-form-item
            label="植物名"
            :label-width="formLabelWidth"
            prop="plantname"
          >
            <el-input v-model.trim="form.plantname" autocomplete="off" />
          </el-form-item> -->
          <!-- 新增PH-->
          <!-- <el-form-item
            label="ph值上限"
            :label-width="formLabelWidth"
            prop="ph"
          >
            <el-input v-model.trim="form.ph" autocomplete="off"
              ><template #append>PH</template></el-input
            >
          </el-form-item> -->
          <!-- 新增ph值上限 -->
          <el-form-item
            label="ph值上限"
            :label-width="formLabelWidth"
            prop="phmax"
          >
            <el-input v-model.trim="form.phmax" autocomplete="off"
              ><template #append>PH</template></el-input
            >
          </el-form-item>
          <!-- 新增ph值下限 -->
          <el-form-item
            label="ph值下限"
            :label-width="formLabelWidth"
            prop="phmin"
          >
            <el-input v-model.trim="form.phmin" autocomplete="off"
              ><template #append>PH</template></el-input
            >
          </el-form-item>
          <!-- 新增土壤湿度 -->
          <!-- <el-form-item
            label="土壤湿度"
            :label-width="formLabelWidth"
            prop="hum"
          >
            <el-input v-model.trim="form.hum" autocomplete="off" />
          </el-form-item> -->
          <!-- 土壤湿度上限 -->
          <el-form-item
            label="土壤湿度上限"
            :label-width="formLabelWidth"
            prop="hummax"
          >
            <el-input v-model.trim="form.hummax" autocomplete="off"
              ><template #append>毫升</template></el-input
            >
          </el-form-item>
          <!-- 土壤湿度下限 -->
          <el-form-item
            label="土壤湿度下限"
            :label-width="formLabelWidth"
            prop="hummin"
          >
            <el-input v-model.trim="form.hummin" autocomplete="off"
              ><template #append>毫升</template></el-input
            >
          </el-form-item>
          <!-- 新增创建人 -->
          <!-- <el-form-item
            label="创建人"
            :label-width="formLabelWidth"
            prop="username"
          >
            <el-input v-model="form.username" autocomplete="off" />
          </el-form-item> -->
          <!-- 创建时间 -->
          <el-form-item
            label="开始时间"
            prop="createtime"
            :label-width="formLabelWidth"
          >
            <el-config-provider :locale="locale">
              <el-date-picker
                v-model="form.createtime"
                type="datetime"
                placeholder="选择开始时间"
                :disabled-date="disabledDate"
                controls-position="right"
              ></el-date-picker>
            </el-config-provider>
          </el-form-item>
          <!-- 结束时间 -->
          <el-form-item
            label="结束时间"
            prop="endtime"
            :label-width="formLabelWidth"
          >
            <el-config-provider :locale="locale">
              <el-date-picker
                v-model="form.endtime"
                type="datetime"
                placeholder="选择结束时间"
                :disabled-date="disabledDate"
                controls-position="right"
              ></el-date-picker>
            </el-config-provider>
          </el-form-item>
          <!-- 新增备注 -->
          <!-- <el-form-item
            label="备注"
            :label-width="formLabelWidth"
            prop="remark"
          >
            <el-input
              v-model.trim="form.remark"
              :rows="2"
              type="textarea"
              placeholder="请输入备注"
              maxlength="30"
              show-word-limit
            />
          </el-form-item> -->
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="dialogFormVisibleAdd = false">取消</el-button>
            <el-button type="primary" @click="submitForm(ruleFormRef)">
              提交
            </el-button>
          </div>
        </template>
      </el-dialog>
    </div>
    <!-- 修改弹窗 -->
    <div>
      <el-dialog v-model="dialogFormVisible" title="修改ph值上下限" width="500">
        <el-form :model="form" ref="ruleFormRefPut" :rules="soilRules">
          <!-- ph值上限 -->
          <el-form-item
            label="ph值上限"
            :label-width="formLabelWidth"
            prop="phmax"
          >
            <el-input v-model.trim="form.phmax" autocomplete="off" />
          </el-form-item>
          <!-- ph值下限 -->
          <el-form-item
            label="ph值下限"
            :label-width="formLabelWidth"
            prop="phmin"
          >
            <el-input v-model.trim="form.phmin" autocomplete="off" />
          </el-form-item>
          <!-- 土壤湿度上限 -->
          <el-form-item
            label="土壤湿度上限"
            :label-width="formLabelWidth"
            prop="hummax"
          >
            <el-input v-model.trim="form.hummax" autocomplete="off" />
          </el-form-item>
          <!-- 土壤湿度下限 -->
          <el-form-item
            label="土壤湿度下限"
            :label-width="formLabelWidth"
            prop="hummin"
          >
            <el-input v-model.trim="form.hummin" autocomplete="off" />
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取消</el-button>
            <el-button type="primary" @click="submitSave(ruleFormRefPut)">
              保存
            </el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup>
import {
  getList,
  getSearch,
  getDelete,
  getAdd,
  getUpdate,
  soildevice,
} from "@/api/Soil/index";
import { reactive, ref, onMounted, computed, onUnmounted } from "vue";
import zhCn from "element-plus/es/locale/lang/zh-cn";
const locale = zhCn;
// 分页参数
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);
const tableData = ref([]);
onMounted(() => {
  getListitem();
  getSoildevice();
});
const timerId = setInterval(() => {
  // 这里是您每3分钟想要执行的函数
  getListitem();
}, 1800000);

onUnmounted(() => {
  clearInterval(timerId); // 组件卸载时清除定时器，避免内存泄漏
});
// 删除弹窗
const dialogFormDelate = ref(false);
// 新增弹窗
const dialogFormVisibleAdd = ref(false);
// 编辑弹窗
const dialogFormVisible = ref(false);
// 新增框ref
const ruleFormRef = ref(null);
//编辑框
const ruleFormRefPut = ref(null);
// 删除框
const ruleFormRefDelete = ref(null);
// 页码更改
const handleCurrentChange = (newPage) => {
  console.log("newPage", newPage);
  currentPage.value = newPage;
  getListitem(newPage);
};

// 每页条数更改
const handleSizeChange = (newSize) => {
  pageSize.value = newSize;
  currentPage.value = 1;
  getListitem(1);
};
// 获取列表数据
const getListitem = () => {
  getList({
    pageNum: currentPage.value,
    pageSize: pageSize.value,
  }).then((res) => {
    tableData.value = res.data.records;
    console.log("tableData.value", tableData.value);
    total.value = res.data.total;
    console.log("tableData.valuetableData.value", tableData.value);
  });
};
// 查询设备状态
const soil = ref([]);
const getSoildevice = () => {
  soildevice().then((res) => {
    soil.value = res;
    if (soil.value.data === null) {
      ElMessage({
        message: "当前没有设备不能新增",
        type: "error",
        plain: true,
      });
    }
    console.log("soildevice.value ", soil.value);
  });
};

//用于限制时间选择器的日期范围
const disabledDate = (time) => {
  return time.getTime() < Date.now() - 86400000;
};
// 设置序号
const indexedData = computed(() => {
  const startIndex = (currentPage.value - 1) * pageSize.value + 1;

  return tableData.value.map((item, index) => ({
    ...item,
    index: startIndex + index,
  }));
});

// 搜索
const Inquireform = ref([]);

// 搜索
const Search = (form) => {
  console.log("搜索内容", form.searchText, form.search);
  if (!form.searchText) {
    ElMessage({
      message: "请输入数据",
      type: "error",
      plain: true,
    });
    getListitem();
  } else {
    getSearch(form.search, form.searchText).then((res) => {
      tableData.value = res.data.records;
      total.value = res.data.total;
      currentPage.value = 1; // 重置当前页为第一页
    });
  }
};
// 清空表单
const resetForm = () => {
  form.sid = "";
  // form.plantname = "";
  form.ph = "";
  form.phmax = "";
  form.phmin = "";
  // form.did = "";
  form.hummax = "";
  form.hummin = "";
  form.hum = "";
  form.username = "";
  form.createtime = "";
  form.endtime = "";
  form.remark = "";
};
// 打开新增对话框重置表单
const handleAddNew = () => {
  resetForm();
  dialogFormVisibleAdd.value = true;
};
//输入框宽度
const formLabelWidth = "140px";
// 校验的内容
const form = reactive({
  sid: "",
  // ph: "",
  // plantname: "",
  phmax: "",
  phmin: "",
  // did: "",
  hummax: "",
  hummin: "",
  // hum: "",
  // remark: "",
  createtime: "",
  endtime: "",
  // username: "",
});
const forms = reactive({
  sid: "",
  remark: "",
});

// 要编辑栏的数据
const openEditDialog = (row) => {
  form.sid = row.sid;
  // form.plantname = row.plantname;
  form.ph = row.ph;
  form.phmax = row.phmax;
  form.phmin = row.phmin;
  form.did = row.did;
  form.hummax = row.hummax;
  form.hummin = row.hummin;
  form.hum = row.hum;
  form.remark = row.remark;
  form.endtime = row.endtime;
  // form.username = row.username;
  // 显示编辑对话框
  dialogFormVisible.value = true;
};
const openEditDelete = (row) => {
  form.sid = row.sid;
  // form.plantname = row.plantname;

  form.remark = row.remark;
  // form.username = row.username;
  // 显示编辑对话框
  dialogFormDelate.value = true;
};
//校验输入的内容
const soilRules = reactive({
  phmax: [
    { required: true, message: "请输入ph值上限,不能大于14", trigger: "blur" },
    { validator: checkPHValue, trigger: "blur" },
  ],
  phmin: [
    { required: true, message: "请输入ph值下限,不能小于0", trigger: "blur" },
    { validator: checkPHMinValue, trigger: "blur" },
  ],
  // plantname: [{ required: true, message: "请输入内容", trigger: "blur" }],
  // did: [{ required: true, message: "请选择设备", trigger: "blur" }],
  // hum: [{ required: true, message: "请输入土壤湿度", trigger: "blur" }],
  hummax: [
    {
      required: true,
      message: "请输入土壤湿度上限制，不能大于100",
      trigger: "blur",
    },
    { validator: checkMaxValue, trigger: "blur" },
  ],
  hummin: [
    {
      required: true,
      message: "请输入土壤湿度下限，不能小于0",
      trigger: "blur",
    },
    { validator: checkHumValue, trigger: "blur" },
  ],
  // username: [{ required: true, message: "请输入创建人姓名", trigger: "blur" }],
  remark: [{ required: true, message: "请输入内容", trigger: "blur" }],
  createtime: [{ required: true, message: "请输入内容", trigger: "blur" }],
  endtime: [
    { required: true, message: "请输入内容", trigger: "blur" },
    { validator: checkTimeValue, trigger: "blur" },
  ],
});
// 校验ph值是否在合理范围内
function checkPHValue(rule, value, callback) {
  if (value === "") {
    return callback(new Error("PH值不能为空，"));
  } else if (value < 0 || value > 14 || value <= form.phmin) {
    return callback(new Error("PH值必须在0到14之间"));
  } else {
    return callback();
  }
}
// 校验ph下限值是否在合理范围内
function checkPHMinValue(rule, value, callback) {
  if (value === "") {
    return callback(new Error("PH值不能为空，"));
  } else if (value < 0 || value > 14 || value >= form.phmax) {
    return callback(new Error("PH下限不能等于或高于上限"));
  } else {
    return callback();
  }
}
function checkMaxValue(rule, value, callback) {
  if (value === "") {
    return callback(new Error("请输入土壤湿度限制不能为空,应在0到100之间"));
  } else if (value < 0 || value > 100 || value <= form.hummin) {
    return callback(new Error("不能等于或低于土壤湿度下限"));
  } else {
    return callback();
  }
}
// 校验湿度上限值是否在合理范围内
function checkHumValue(rule, value, callback) {
  if (value === "") {
    return callback(new Error("请输入土壤湿度限制不能为空,应在0到100之间"));
  } else if (value < 0 || value > 100 || value >= form.hummax) {
    return callback(new Error("不能等于或高于土壤湿度上限"));
  } else {
    return callback();
  }
}
// 校验时间结束是否在合理范围内
function checkTimeValue(rule, value, callback) {
  if (value === "") {
    return callback(new Error("请输入内容"));
  } else if (value <= form.createtime) {
    return callback(new Error("不能比开始时间早或相等"));
  } else {
    return callback();
  }
}

const formatDate = (date) => {
  let dateObj = new Date(date);
  const year = dateObj.getFullYear();
  const month = String(dateObj.getMonth() + 1).padStart(2, "0"); // 月份从0开始计数，需加1并补0
  const day = String(dateObj.getDate()).padStart(2, "0");
  const hours = String(dateObj.getHours()).padStart(2, "0");
  const minutes = String(dateObj.getMinutes()).padStart(2, "0");
  const seconds = String(dateObj.getSeconds()).padStart(2, "0");
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};

//新增提交按钮
const submitForm = (ruleFormRef) => {
  // console.log("ruleFormRef", ruleFormRef);
  // 验证表单
  ruleFormRef.validate((valid) => {
    if (valid) {
      // 验证通过，提交表单
      // console.log(form, "------");
      form.createtime = formatDate(form.createtime);
      form.endtime = formatDate(form.endtime);
      getAdd(form)
        .then((res) => {
          if (res.code == 200) {
            // 关闭对话框
            dialogFormVisibleAdd.value = false;
            // 重新获取列表数据
            getListitem();
          } else {
            // 处理错误情况
            console.error("添加失败:", res.message);
          }
        })
        .catch((error) => {
          console.error("请求错误:", error);
        });
    } else {
      // 验证失败，提示用户
      console.log("验证失败");
    }
  });
};
//编辑
const submitSave = (ruleFormRefPut) => {
  console.log("ruleFormRefPut", ruleFormRefPut);
  ruleFormRefPut.validate((valid) => {
    if (valid) {
      // 验证通过，提交表单
      getUpdate(form)
        .then((res) => {
          if (res.code == 200) {
            // 关闭对话框
            dialogFormVisible.value = false;
            resetForm();
            // 重新获取列表数据
            getListitem();
          } else {
            // 处理错误情况
            console.error("编辑失败:", res.message);
          }
        })
        .catch((error) => {
          console.error("请求错误:", error);
        });
    } else {
      // 验证失败，提示用户
      console.log("验证失败");
    }
  });
};
//修改删除原因
const submitDelete = (ruleFormRefDelete) => {
  console.log("ruleFormRefDelete", ruleFormRefDelete);
  ruleFormRefDelete.validate((valid) => {
    if (valid) {
      // 验证通过，提交表单
      getUpdate(form)
        .then((res) => {
          if (res.code == 200) {
            console.log("formform", form);

            // 关闭对话框
            dialogFormDelate.value = false;
            dialogDelate(form);
            resetForm();
            // 重新获取列表数据
            getListitem();
          } else {
            // 处理错误情况
            console.error("编辑失败:", res.message);
          }
        })
        .catch((error) => {
          console.error("请求错误:", error);
        });
    } else {
      // 验证失败，提示用户
      console.log("验证失败");
    }
  });
};
// 删除
const dialogDelate = (row) => {
  console.log("删除------", row);

  getDelete(row.sid)
    .then((res) => {
      console.log("res---------", res);
      if (res.code == 200) {
        ElMessage({
          type: "success",
          message: "删除成功",
        });
        // 重新获取列表数据
        getListitem();
      } else {
        // 删除失败的提示
        ElMessage({
          type: "error",
          message: "删除失败: " + res.message,
        });
      }
    })
    .catch((error) => {
      console.error("请求错误:", error);
      // 请求错误的提示
      ElMessage({
        type: "error",
        message: "请求错误",
      });
    });
};
</script>
<style lang="scss" scoped>
.top {
  height: 2vh;
  padding: 10px 0;
  border-radius: 5px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
  margin-top: 10px;
  /*顶部标题 */
  // .title01 {
  //   font-size: 20px;
  //   font-weight: bold;
  //   border-left: 5px solid #409eff;
  //   padding-left: 10px;
  // }
  .right {
    display: flex;
    .query {
      display: flex;
      margin-right: 20px;
    }
  }
}
.max {
  color: #ff0000;
}
.deleted {
  color: #000000;
}
</style>
